<?php
namespace App\Shop\Logic;

use App\Http\Logic\BaseLogic;
use App\Models\SwtMachine;
use App\Models\SwtMerchant;
use App\Models\SwtMerchantProfit;
use Illuminate\Support\Facades\Storage;

class MachineLogic extends BaseLogic
{
    public static function getMachineList($params)
    {
        $page_no = 1;

        if(key_exists('page_no', $params) && $params['page_no']) {
            $page_no = $params['page_no'];
        }

        $page_size = 10;

        if(key_exists('page_size', $params) && $params['page_size']) {
            $page_size = $params['page_size'];
        }

        $offset = ($page_no - 1) * $page_size;

        $where = [];

        if(key_exists('machine_name', $params) && $params['machine_name']) {
            $where[] = ['machine_name', 'like', '%'.$params['machine_name'].'%'];
        }

        $list = SwtMachine::where($where)
            -> orderBy('created_at','desc')
            -> limit($page_size)
            -> offset($offset)
            -> get();

        $count = SwtMachine::where($where)->count();

        $arr = [];

        foreach ($list as $item)
        {
            $arr[] = [
                'id'           => $item['id'],
                'machine_name' => $item['machine_name'],
                'machine_no'   => $item['machine_no'],
                'file'         => asset(Storage::url($item['file_path'])),
                'create_time'  => $item['created_at']->format('Y-m-d H:i:s'),
                'update_time'  => $item['updated_at']->format('Y-m-d H:i:s')
            ];
        }

        $data = [
            'list'          => $arr,
            'page_no'       => $page_no,
            'page_size'     => $page_size,
            'count'         => $count,
        ];

        return $data;
    }
    /**
     * @notes 获取设备列表
     * @param $merchant_id
     * @param $page_no
     * @param $page_size
     * @return array
     * @author Evil丿
     * @date 2024/08/09 10:19
     */
    public static function getMachineListByMerchantId($params) {
        $page_no = 1;

        if(key_exists('page_no', $params) && $params['page_no']) {
            $page_no = $params['page_no'];
        }

        $page_size = 10;

        if(key_exists('page_size', $params) && $params['page_size']) {
            $page_size = $params['page_size'];
        }

        $offset = ($page_no - 1) * $page_size;

        $merchant_id = $params['merchant_id'];

        $list = SwtMerchant::firstWhere('id', $merchant_id);

        $res = $list
            -> machines()
            -> orderBy('created_at','desc')
            -> limit($page_size)
            -> offset($offset)
            -> get();

        $count = SwtMerchant::withCount('machines')->find($merchant_id);

        $arr = [];

        if($res) {
            $res = $res -> toArray();
        }

        foreach ($res as $item)
        {
            $arr[] = [
                'id'            => $item['id'],
                'machine_sn'    => $item['machine_name'],
                'file'          => asset(Storage::url($item['file_path'])),
                'create_time'   => $item['created_at'],
                'update_time'   => $item['updated_at']
            ];
        }

        $data = [
            'list'          => $arr,
            'page_no'       => $page_no,
            'page_size'     => $page_size,
            'count'         => $count->machines_count,
            'more'          => count($res) >= $page_size
        ];

        return $data;
    }

    /**
     * @notes 根据商户ID获取商户设备极其收益
     * @param $merchant_id
     * @param $page_no
     * @param $page_size
     * @return array
     * @author Evil丿
     * @date 2024/08/07 15:11
     */
    public static function getMachineProfitListByMerchantId($params)
    {
        $data = self::getMachineListByMerchantId($params);

        foreach($data['list'] as &$item){
            $sale_price_add = SwtMerchantProfit::join('swt_order','swt_merchant_profit.order_id','=','swt_order.id','left')
                -> where('swt_merchant_profit.merchant_id', $params['merchant_id'])
                -> where('swt_order.machine_id', $item['id'])
                -> where('swt_merchant_profit.type', 0)
                -> sum('swt_merchant_profit.amount');

            $sale_price_sub = SwtMerchantProfit::join('swt_order','swt_merchant_profit.order_id','=','swt_order.id','left')
                -> where('swt_merchant_profit.merchant_id', $params['merchant_id'])
                -> where('swt_order.machine_id', $item['id'])
                -> where('swt_merchant_profit.type', 1)
                -> sum('swt_merchant_profit.amount');

            $profit_price_add = SwtMerchantProfit::join('swt_order','swt_merchant_profit.order_id','=','swt_order.id')
                -> where('swt_merchant_profit.merchant_id', $params['merchant_id'])
                -> where('swt_order.machine_id', $item['id'])
                -> where('swt_merchant_profit.type', 0)
                -> sum('swt_merchant_profit.profit');

            $profit_price_sub = SwtMerchantProfit::join('swt_order','swt_merchant_profit.order_id','=','swt_order.id')
                -> where('swt_merchant_profit.merchant_id', $params['merchant_id'])
                -> where('swt_order.machine_id', $item['id'])
                -> where('swt_merchant_profit.type', 1)
                -> sum('swt_merchant_profit.profit');

            $item['amount_sale'] = (float) bcdiv($sale_price_add - $sale_price_sub, 100 ,2);
            $item['amount_profit'] = (float) bcdiv($profit_price_add - $profit_price_sub, 100 ,2);
        }

        return $data;
    }

    public static function getYesterdayMachineProfitListByMerchantId($params)
    {
        $data = self::getMachineListByMerchantId($params);

        foreach($data['list'] as &$item){
            $profit_price_add = SwtMerchantProfit::join('swt_order','swt_merchant_profit.order_id','=','swt_order.id')
                -> where('swt_merchant_profit.merchant_id', $params['merchant_id'])
                -> where('swt_order.machine_id', $item['id'])
                -> where('swt_merchant_profit.type', 0)
                -> whereDate('swt_merchant_profit.created_at', date('Y-m-d', strtotime('-1 day')))
                -> sum('swt_merchant_profit.profit');

            $profit_price_sub = SwtMerchantProfit::join('swt_order','swt_merchant_profit.order_id','=','swt_order.id')
                -> where('swt_merchant_profit.merchant_id', $params['merchant_id'])
                -> where('swt_order.machine_id', $item['id'])
                -> where('swt_merchant_profit.type', 1)
                -> whereDate('swt_merchant_profit.created_at', date('Y-m-d', strtotime('-1 day')))
                -> sum('swt_merchant_profit.profit');

            $item['amount_profit'] = (float) bcdiv($profit_price_add - $profit_price_sub, 100 ,2);
        }

        return $data;
    }

    public static function getYesterdayDeviceProfitByDeviceId($params)
    {
        $model = new SwtMerchantProfit();

        $profit_price_add = $model
            -> where('machine_id', $params['device_id'])
            -> where('type', 0)
            -> whereDate('created_at', date('Y-m-d', strtotime('-1 day')))
            -> sum('profit');

        $add = $profit_price_add ?? 0;

        $profit_price_sub = $model
            -> where('machine_id', $params['device_id'])
            -> where('type', 1)
            -> whereDate('created_at', date('Y-m-d', strtotime('-1 day')))
            -> sum('profit');

        $sub = $profit_price_sub ?? 0;

        return [
            'amount_profit' => (float) bcdiv($add - $sub, 100 ,2)
        ];
    }
}
